package com.panopset.db;

import java.io.StringWriter;

/**
 * Foreign key field.
 *
 * @author Karl Dinwiddie
 *
 */
public class FieldIdFK extends DataField {

    /**
     * Foreign key field.
     */
    private final DataField fk;

    /**
     * Table description.
     */
    private final TableDescription<?> fkt;

    /**
     * @param fkTable
     *            Foreign key table.
     */
    public FieldIdFK(final TableDescription<?> fkTable) {
        super(fkTable.getTableBindField().getName());
        setIndexed();
        fk = fkTable.getTableBindField();
        fkt = fkTable;
    }

    @Override
    public String getAttributes() {
        return fk.getAttributes();
    }

    private String fkAttrs;

    
    public String getAdditionalAttributes() {
        if (fkAttrs == null) {
            StringWriter sw = new StringWriter();
            sw.append(" foreign key(");
            sw.append(fk.getName());
            sw.append(") references ");
            sw.append(fkt.getFullTableName());
            sw.append("(id)");
            fkAttrs = sw.toString();
        }
        return fkAttrs;
    }

    /**
     * @return TableDescription of bound table.
     */
    public TableDescription<?> getBoundTable() {
        return fkt;
    }
}
